# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: inkyu

import collections

from coin.exchange.util.feed_checker.per_product.book_checker import (PerProductBookChecker,
                                                                      PerProductBookCheckerStatus)
from coin.exchange.util.feed_checker.per_product.trade_checker import (PerProductTradeChecker,
                                                                       PerProductTradeCheckerStatus)

PerProductFeedCheckerStatus = collections.namedtuple(
    'PerProductFeedCheckerStatus',
    ('product',) + PerProductBookCheckerStatus._fields + PerProductTradeCheckerStatus._fields)


class PerProductFeedChecker(object):
  def __init__(self, *, product, config, timestamp):
    self._product = product
    self._config = config
    self._timestamp = timestamp
    self._book_checker = PerProductBookChecker(product=product, config=config, timestamp=timestamp)
    self._trade_checker = PerProductTradeChecker(product=product,
                                                 config=config,
                                                 timestamp=timestamp)

    self._book_count = 0
    self._trade_count = 0
    self._valid = True

  @property
  def book_count(self):
    return self._book_count

  @property
  def trade_count(self):
    return self._trade_count

  @property
  def valid(self):
    return self._valid

  def on_book(self, *, book, timestamp):
    if not self._valid:
      return
    self._book_checker.on_book(book=book, timestamp=timestamp)
    self._book_count = self._book_checker.count
    if not self._book_checker.valid:
      self._valid = False

  def on_trade(self, *, trade_event, timestamp):
    if not self._valid:
      return
    self._trade_checker.on_trade(trade_event=trade_event, timestamp=timestamp)
    self._trade_count = self._trade_checker.count
    if not self._trade_checker.valid:
      self._valid = False

  def update_timestamp(self, *, timestamp):
    if not self._valid:
      return
    self._book_checker.update_timestamp(timestamp=timestamp)
    if not self._book_checker.valid:
      self._valid = False
      return
    self._trade_checker.update_timestamp(timestamp=timestamp)
    if not self._trade_checker.valid:
      self._valid = False
      return

  def get_status(self, *, timestamp):
    return PerProductFeedCheckerStatus(
        product=self._product,
        **self._book_checker.get_status(timestamp=timestamp)._asdict(),
        **self._trade_checker.get_status(timestamp=timestamp)._asdict())
